package com.miaoa.jbox2d.demo;

import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.ColorMatrix;
import android.graphics.ColorMatrixColorFilter;
import android.graphics.Paint;
import android.graphics.drawable.Drawable;
import android.graphics.drawable.Icon;
import android.media.ThumbnailUtils;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.view.View;

import androidx.annotation.RequiresApi;

import java.io.BufferedOutputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;

public class BitmapUtil {
    public static boolean saveImageToGallery(Context context, Bitmap bmp) {
        if (bmp == null) {
            return false;
        }
        if (bmp.isRecycled()) {
            return false;
        }
        // 首先保存图片
        String storePath = Environment.getExternalStorageDirectory().getAbsolutePath() + File.separator + "chai_chai";
        File appDir = new File(storePath);
        if (!appDir.exists()) {
            if (!appDir.mkdir()) {
                return false;
            }
        }
        String fileName = "chai_chai_" + System.currentTimeMillis() + ".jpg";
        File file = new File(appDir, fileName);
        try {
            FileOutputStream fos = new FileOutputStream(file);
            //通过io流的方式来压缩保存图片
            boolean isSuccess = bmp.compress(Bitmap.CompressFormat.JPEG, 100, fos);
            fos.flush();
            fos.close();

            //保存图片后发送广播通知更新数据库
            Uri uri = Uri.fromFile(file);
            context.sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, uri));
            return isSuccess;
        } catch (IOException e) {
            e.printStackTrace();
        }
        return false;
    }

    public static boolean saveImage(String fileName) {
        if (!Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
            return false;
        }
        Bitmap bmp = BitmapFactory.decodeFile(fileName);
        if (bmp == null) {
            return false;
        }
        File file = new File(fileName);
        if (file.exists()) {
            boolean isDelete = file.delete();
            if (!isDelete) {
                return false;
            }
        }
        try {
            FileOutputStream fos = new FileOutputStream(file);
            //通过io流的方式来压缩保存图片
            boolean isSuccess = bmp.compress(Bitmap.CompressFormat.PNG, 85, fos);
            fos.flush();
            fos.close();
            return isSuccess;
        } catch (IOException e) {
            e.printStackTrace();
        }
        return false;
    }

    /**
     * 将bitmap黑白化
     *
     * @param bmp
     * @return
     */
    public static Bitmap convertBlackWhite(Bitmap bmp) {
        int width = bmp.getWidth();
        int height = bmp.getHeight();
        int[] pixels = new int[width * height];
        bmp.getPixels(pixels, 0, width, 0, 0, width, height);
        int alpha = 0xFF << 24;
        for (int i = 0; i < height; i++) {
            for (int j = 0; j < width; j++) {
                int grey = pixels[width * i + j];

                // 分离三原色
                int red = ((grey & 0x00FF0000) >> 16);
                int green = ((grey & 0x0000FF00) >> 8);
                int blue = (grey & 0x000000FF);

                // 转化成灰度像素
                grey = (int) (red * 0.3 + green * 0.59 + blue * 0.11);
                grey = alpha | (grey << 16) | (grey << 8) | grey;
                pixels[width * i + j] = grey;
            }
        }
        // 新建图片
        Bitmap newbmp = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
        newbmp.setPixels(pixels, 0, width, 0, 0, width, height);
        Bitmap resizeBmp = ThumbnailUtils.extractThumbnail(newbmp, width,
                height);

        return resizeBmp;
    }

    // 5. Drawable----> Bitmap
    public static Bitmap convertBlackWhite(Drawable drawable) {

        // 获取 drawable 长宽
        int width = drawable.getIntrinsicWidth();
        int height = drawable.getIntrinsicHeight();

        drawable.setBounds(0, 0, width, height);

        // 获取drawable的颜色格式
//        Bitmap.Config config = drawable.getOpacity() != PixelFormat.OPAQUE ? Bitmap.Config.ARGB_8888
//                : Bitmap.Config.RGB_565;
        // 创建bitmap
        Bitmap bitmap = Bitmap.createBitmap(width, height, Bitmap.Config.RGB_565);
        // 创建bitmap画布
        Canvas canvas = new Canvas(bitmap);
        //创建画笔
        Paint paint = new Paint();
        //创建颜色矩阵
        ColorMatrix matrix = new ColorMatrix();
        //设置颜色矩阵的饱和度:0代表灰色,1表示原图
        matrix.setSaturation(0);
        //颜色过滤器
        ColorMatrixColorFilter cmcf = new ColorMatrixColorFilter(matrix);
        //设置画笔颜色过滤器
        paint.setColorFilter(cmcf);
        // 将drawable 内容画到画布中
//        drawable.draw(canvas);
        canvas.drawBitmap(bitmap, 0, 0, paint);
        return bitmap;
    }

    /**
     * 获取未显示的view宽高
     *
     * @param view
     * @return
     */
    public static int[] getUnDisplayViewSize(View view) {
        int[] size = new int[2];
        int width = View.MeasureSpec.makeMeasureSpec(0,
                View.MeasureSpec.UNSPECIFIED);
        int height = View.MeasureSpec.makeMeasureSpec(0,
                View.MeasureSpec.UNSPECIFIED);
        view.measure(width, height);
        size[0] = view.getMeasuredWidth();
        size[1] = view.getMeasuredHeight();
        return size;
    }

    /**
     * view转为bitmap
     *
     * @param view
     * @return
     */
    public static Bitmap createViewBitmap(View view) {
        int[] viewSize = getUnDisplayViewSize(view);
        int width = viewSize[0];
        int height = viewSize[1];
        Bitmap bitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
        if (bitmap != null) {
            Canvas canvas = new Canvas(bitmap);
            int top = view.getTop();
            int bottom = view.getBottom();
            int left = view.getLeft();
            int right = view.getRight();
            view.layout(0, 0, width, height);
            view.draw(canvas);
            // 需要还原view的位置，不然导致后续view的展示操作出现错位问题
            view.layout(left, top, right, bottom);
            return bitmap;
        }
        return null;
    }

    /**
     * view 转 Icon
     *
     * @param view
     * @param viewSize
     * @return
     */
    @RequiresApi(api = Build.VERSION_CODES.M)
    public static Icon createViewIcon(View view, int[] viewSize) {
        Bitmap bitmap = Bitmap.createBitmap(viewSize[0], viewSize[1], Bitmap.Config.ARGB_8888);
        if (bitmap != null) {
            Canvas canvas = new Canvas(bitmap);
            int top = view.getTop();
            int bottom = view.getBottom();
            int left = view.getLeft();
            int right = view.getRight();
            view.layout(0, 0, viewSize[0], viewSize[1]);
            view.draw(canvas);
            canvas.setBitmap(null);
            // 需要还原view的位置，不然导致后续view的展示操作出现错位问题
            view.layout(left, top, right, bottom);
            Icon icon = null;
            try {
                ByteArrayOutputStream baos = new ByteArrayOutputStream();
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
                    bitmap.compress(Bitmap.CompressFormat.WEBP_LOSSY, 100, baos);
                } else {
                    bitmap.compress(Bitmap.CompressFormat.WEBP, 100, baos);
                }
                icon = Icon.createWithData(baos.toByteArray(), 0, baos.size());
                baos.close();
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                try {
                    bitmap.recycle();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
            return icon;
        }
        return null;
    }

    /**
     * bitmap 转 Icon
     *
     * @param bitmap
     * @return
     */
    @RequiresApi(api = Build.VERSION_CODES.M)
    public static Icon bitmapToIcon(Bitmap bitmap) {
        if (bitmap != null && !bitmap.isRecycled()) {
            Icon icon = null;
            try {
                ByteArrayOutputStream baos = new ByteArrayOutputStream();
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
                    bitmap.compress(Bitmap.CompressFormat.WEBP_LOSSY, 100, baos);
                } else {
                    bitmap.compress(Bitmap.CompressFormat.WEBP, 100, baos);
                }
                icon = Icon.createWithData(baos.toByteArray(), 0, baos.size());
                baos.close();
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                try {
                    bitmap.recycle();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
            return icon;
        }
        return null;
    }

}
